<script lang="ts" setup>
import { nextTick, onBeforeMount, onMounted, reactive, ref, toRefs } from 'vue';

import { StorageManager } from '@vben-core/shared/cache';

import {
  ElButton,
  ElDialog,
  ElInput,
  ElMessage,
  ElOption,
  ElSelect,
  ElTag,
} from 'element-plus';

import { fileTagApi, segmentApi } from '#/api';
import { fileTag2FileSegment, getKnowledgeInfo } from '#/utils';

const props = defineProps({
  isAddTagShow: {
    type: Boolean,
    default: false,
  },
  dataName: {
    default: 'FILE NAME',
    type: String,
  },
  dataId: {
    default: '',
    type: String,
  },
  isPublic: {
    default: false,
    type: Boolean,
  },
});

const emit = defineEmits(['closeAddTagDialog']);

const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});

const { isAddTagShow, dataName, dataId } = toRefs(props);
const dataTypeOptions = ['矢量', '栅格', '表格', '音频', '视频', '图片']; // 可扩展
const selectedType = ref(''); // 用于绑定选择的值
const isAdmin = ref(false); // 管理员权限
const tagPermission = ref(false);
const AppOptions = import.meta.env;
const formData = reactive({
  数据类型: [], // 单值
  地理位置: [], // 多值
  应用特性: [], // 多值
  其他描述: [], // 多值
});
// 输入框状态
const inputVisible = reactive({
  数据类型: false,
  地理位置: false,
  应用特性: false,
  其他描述: false,
});

// 输入框值
const inputValue = reactive({
  数据类型: '',
  地理位置: '',
  应用特性: '',
  其他描述: '',
});
onBeforeMount(() => {
  const email = storageManager.getItem('email');
  if (email === `${AppOptions.VITE_ADMIN_EMAIL}`) {
    isAdmin.value = true;
  }
  if ((isAdmin.value && props.isPublic) || !props.isPublic) {
    tagPermission.value = true;
  }
});

// 处理下拉框选择
const handleTypeSelect = (value: string) => {
  formData['数据类型'] = [value]; // 将选中的值保存到 formData
  selectedType.value = ''; // 清空下拉框绑定值，避免 UI 混乱
};

// 显示输入框
const showInput = async (type: string) => {
  inputVisible[type] = true;
  await nextTick();
};

// 输入确认
const handleInputConfirm = (type: string) => {
  const value = inputValue[type];
  if (value) {
    if (type === '数据类型') {
      formData[type] = [value]; // 仅允许一个值
    } else {
      formData[type].push(value); // 多值
    }
    inputValue[type] = '';
  }
  inputVisible[type] = false;
};

// 删除标签
const handleClose = (type: string, tag: string) => {
  const index = formData[type].indexOf(tag);
  if (index !== -1) {
    formData[type].splice(index, 1);
  }
};
// 重置表单数据为默认结构
const resetFormData = () => {
  formData['数据类型'] = [];
  formData['地理位置'] = [];
  formData['应用特性'] = [];
  formData['其他描述'] = [];
};
// 重置标签
const handleResetTags = async () => {
  try {
    resetFormData();
    ElMessage.success('标签已重置！');
  } catch (error) {
    console.error('重置标签失败：', error);
  }
};
// 关闭对话框
const closeAddTagDialog = () => {
  emit('closeAddTagDialog');
};
// 格式化表单数据
const formatFormData = (data: Record<string, any>) => {
  return {
    type: data['数据类型'][0] || null, // 数据类型为单值，取第一个，没有则为 null
    location: data['地理位置'].length > 0 ? data['地理位置'] : null, // 地理位置为多值数组
    attr: data['应用特性'].length > 0 ? data['应用特性'] : null, // 应用特性为多值数组
    other: data['其他描述'].length > 0 ? data['其他描述'] : null, // 其他描述为多值数组
  };
};
// 提交表单
const handleSubmit = async () => {
  try {
    // 格式化数据为后端需要的结构
    const payload = formatFormData(formData) as any;
    // console.log('提交标签：', payload); // 打印格式化后的数据
    if (props.isPublic) {
      // console.log(tagPermission.value); // 打印格式化后的数据
      await fileTagApi.updatePublicFileTag(dataId.value, payload);
      ElMessage.success('标签提交成功！');
    } else {
      // console.log(tagPermission.value);
      await fileTagApi.updateFileTag(dataId.value, payload); // 传递 fileId 和标签数据
      ElMessage.success('标签提交成功！');

      // 个人标签更新，需要更新知识库
      const { datasetId, documentId } = await getKnowledgeInfo();
      // console.log(datasetId);
      if (!(datasetId && documentId)) {
        // console.log(datasetId, documentId);
        ElMessage.warning('知识库不存在，无法同步到知识库');
        closeAddTagDialog();

        return;
      }
      const {
        data: { data: segments },
      } = await segmentApi.querySegments(datasetId, documentId, dataId.value);
      // 更新知识库
      payload.fileId = dataId.value;
      payload.fileName = dataName.value;
      const text = fileTag2FileSegment([payload])
        .map((item) => JSON.stringify(item, null, 2))
        .join('#');
      // console.log(segments);
      if (segments.length > 0) {
        await segmentApi.deleteSegment(datasetId, documentId, segments[0].id);
      }
      await segmentApi.addSegment(datasetId, documentId, [{ content: text }]);
      ElMessage.success('已同步到知识库！');
    }
    // console.log('222');
    closeAddTagDialog();
  } catch (error) {
    console.error('标签提交失败：', error);
  }
};

// 转换后端数据为前端需要的格式
const mapBackendToFormData = (backendData: Record<string, any>) => {
  return {
    数据类型: backendData.type ? [backendData.type] : [], // 将单值字段转为数组格式
    地理位置: backendData.location || [], // 如果是 null，用空数组代替
    应用特性: backendData.attr || [],
    其他描述: backendData.other || [],
  };
};
// 获取标签接口调用
const getFileTag = async (fileId: string) => {
  return await fileTagApi.getFileTag(fileId);
};

const initializeTags = async () => {
  try {
    const response = await getFileTag(dataId.value);

    if (response && response.data) {
      const backendData = response.data;

      // 转换后端数据为前端格式
      const formattedData = mapBackendToFormData(backendData);
      Object.keys(formData).forEach((key) => {
        formData[key] = formattedData[key] || [];
      });
    } else {
      resetFormData(); // 如果没有数据，重置为默认空数据
    }
  } catch (error) {
    console.warn('获取标签失败，使用默认空表单：', error);
    resetFormData();
  }
};

onMounted(async () => {
  await initializeTags();
});
</script>
<template>
  <div>
    <ElDialog
      draggable
      class="dialog-title"
      v-model="isAddTagShow"
      width="35vw"
      v-if="isAddTagShow"
      align-center
      :destroy-on-close="true"
      @close="closeAddTagDialog()"
      :close-on-click-modal="false"
    >
      <template #header>
        <div class="file-text-header">
          <h4 style="color: rgb(48 45 45)">{{ dataName }}</h4>
        </div>
      </template>

      <div class="tag-form">
        <!-- 数据类型 -->
        <div class="form-item">
          <div class="label">数据类型：</div>
          <div class="tag-container">
            <ElTag
              v-if="formData['数据类型'].length > 0"
              :key="formData['数据类型'][0]"
              :closable="tagPermission"
              @close="handleClose('数据类型', formData['数据类型'][0])"
              effect="light"
              size="large"
              round
              class="tag-item"
            >
              {{ formData['数据类型'][0] }}
            </ElTag>

            <ElSelect
              v-if="formData['数据类型'].length === 0"
              v-model="selectedType"
              placeholder="请选择数据类型"
              size="medium"
              class="type-select"
              @change="handleTypeSelect"
              :disabled="!tagPermission"
            >
              <ElOption
                v-for="option in dataTypeOptions"
                :key="option"
                :label="option"
                :value="option"
              />
            </ElSelect>
          </div>
        </div>

        <!-- 地理位置 -->
        <div class="form-item">
          <div class="label">地理位置：</div>
          <div class="tag-container">
            <ElTag
              v-for="tag in formData['地理位置']"
              :key="tag"
              :closable="tagPermission"
              @close="handleClose('地理位置', tag)"
              effect="light"
              size="large"
              round
              class="tag-item"
              type="success"
            >
              {{ tag }}
            </ElTag>
            <ElInput
              v-if="inputVisible['地理位置']"
              v-model="inputValue['地理位置']"
              class="tag-input"
              size="small"
              @keyup.enter="handleInputConfirm('地理位置')"
              @blur="handleInputConfirm('地理位置')"
              :disabled="!tagPermission"
            />
            <ElButton
              type="success"
              plain
              round
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput('地理位置')"
              :disabled="!tagPermission"
            >
              + 添加
            </ElButton>
          </div>
        </div>

        <!-- 应用特性 -->
        <div class="form-item">
          <div class="label">应用特性：</div>
          <div class="tag-container">
            <ElTag
              v-for="tag in formData['应用特性']"
              :key="tag"
              :closable="tagPermission"
              @close="handleClose('应用特性', tag)"
              effect="light"
              size="large"
              round
              class="tag-item"
              type="warning"
            >
              {{ tag }}
            </ElTag>
            <ElInput
              v-if="inputVisible['应用特性']"
              v-model="inputValue['应用特性']"
              class="tag-input"
              size="small"
              @keyup.enter="handleInputConfirm('应用特性')"
              @blur="handleInputConfirm('应用特性')"
              :disabled="!tagPermission"
            />
            <ElButton
              type="warning"
              plain
              round
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput('应用特性')"
              :disabled="!tagPermission"
            >
              + 添加
            </ElButton>
          </div>
        </div>

        <!-- 其他描述 -->
        <div class="form-item">
          <div class="label">其他描述：</div>
          <div class="tag-container">
            <ElTag
              v-for="tag in formData['其他描述']"
              :key="tag"
              :closable="tagPermission"
              @close="handleClose('其他描述', tag)"
              effect="light"
              size="large"
              round
              class="tag-item"
              type="danger"
            >
              {{ tag }}
            </ElTag>
            <ElInput
              v-if="inputVisible['其他描述']"
              v-model="inputValue['其他描述']"
              class="tag-input"
              size="small"
              @keyup.enter="handleInputConfirm('其他描述')"
              @blur="handleInputConfirm('其他描述')"
              :disabled="!tagPermission"
            />
            <ElButton
              type="danger"
              plain
              round
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput('其他描述')"
              :disabled="!tagPermission"
            >
              + 添加
            </ElButton>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <ElButton
            class="mybtn"
            @click="handleResetTags()"
            :disabled="!tagPermission"
            >重置
          </ElButton>
          <ElButton
            class="mybtn"
            type="primary"
            @click="handleSubmit"
            :disabled="!tagPermission"
            >确定
          </ElButton>
          <ElButton class="mybtn" @click="closeAddTagDialog()">取消</ElButton>
        </span>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.tag-form {
  padding: 20px;
}

.form-item {
  margin-bottom: 20px;
}

.label {
  margin-bottom: 10px;
  font-size: medium;
  font-weight: bold;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin-right: 8px;
}

.tag-input {
  width: auto;
  height: 32px;
  margin-right: 8px;
}

.button-new-tag {
  height: 32px;
  padding-top: 0;
  padding-bottom: 0;
}

.file-text-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  padding-top: 10px;
  padding-left: 20px;
  font-size: 25px;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.mybtn {
  width: 80px;
  height: 30px;
  font-weight: bolder;
  letter-spacing: 1px;
  border-radius: 3px;
}

.type-select {
  width: 145px;
}
</style>
